package org.pi.common.vision.tool

import org.pi.common.matrix.FloatMatrix

trait BlurToolTrait {
	private var tempMatrix : FloatMatrix = null

	def createHanningFilter(n : Int) = {
		val res = FloatMatrix(n)
		var x = 0;
		while (x < n) {
			res(x) = 0.5f * (1.0-Math.cos(2.0*Math.Pi*(x+1).toDouble/(n+1).toDouble)).toFloat;
			x += 1
		}
		res
	}
	
	def hanningBlur(data: FloatMatrix, n: Int) : FloatMatrix = hanningBlur(data, n, null, BorderMode.Zero)
	
	def hanningBlur(data: FloatMatrix, n: Int, resultParam: FloatMatrix = null, borderMode: BorderMode.Value = BorderMode.Zero) : FloatMatrix = {
		val filter = createHanningFilter(n)
		var result = resultParam
		if (data.shape.length==2) {
			tempMatrix = ConvolutionTool.filter2Seperated(data, filter, tempMatrix, 0, borderMode, NormalizeMode.Normalize)
			result = ConvolutionTool.filter2Seperated(tempMatrix, filter, result, 1, borderMode, NormalizeMode.Normalize)
		}
		else {
			throw new Error("unsupported data dimension size")
		}
		result
	}
}

object BlurTool extends BlurToolTrait {
	// =====================
	// test
	// =====================
	def main(arg: Array[String]): Unit = {
		println("BlurTool Demo")
		import org.pi.common.vision.Api.imread
		import org.pi.common.vision.Api.imwrite
		import org.pi.common.vision.Api.rgb2gray
		import org.pi.common.time.Api._
		
		val c = imread("data/blume2.png")
		val g = rgb2gray(c)
		var b : FloatMatrix = null;
		var b2 : FloatMatrix = null;
		var k: Int =0;
		for (k <- 0 until 10) {
			printlnTicToc("hanning blur (bordermode = zero)") {
				// blur image with a border of zero
				b = hanningBlur(g,11)
			}
			printlnTicToc("hanning blur (bordermode = replicate)") {
				// blur image with a replicated border
				b2 = hanningBlur(g,11, borderMode = BorderMode.Replicate)
			}
		}

		imwrite("gray.png",g)
		imwrite("blurred.png",b)
		imwrite("blurred2.png",b2)

		println("end Blur demo")
	}
}